from flask import Flask, render_template
from flask_cors import CORS
from app.models.models import db
from app.routes.team_routes import teams
from app.routes.match_routes import matches
import os
from datetime import datetime

def create_app():
    app = Flask(__name__, 
                static_folder='static',
                template_folder='templates')
    
    # 配置 CORS
    CORS(app, resources={
        r"/api/*": {
            "origins": ["*"],
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization"]
        }
    })
    
    # 配置数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///esports.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 初始化数据库
    db.init_app(app)
    
    # 注册蓝图
    app.register_blueprint(teams)
    app.register_blueprint(matches)

    # 添加路由处理
    @app.route('/')
    def index():
        return render_template('home.html')

    @app.route('/home.html')
    def home():
        return render_template('home.html')

    @app.route('/zhandui.html')
    def zhandui():
        return render_template('zhandui.html')

    @app.route('/stats.html')
    def stats():
        return render_template('stats.html')
        
    @app.route('/team_edit.html')
    def team_edit():
        return render_template('team_edit.html')
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
        
        # 添加示例数据
        from app.models.models import Team, Match
        if Team.query.count() == 0:
            teams_data = [
                Team(name='T1', league='LCK', game='英雄联盟', total_matches=20, wins=13),
                Team(name='GEN', league='LCK', game='英雄联盟', total_matches=15, wins=9),
                Team(name='DRX', league='LCK', game='英雄联盟', total_matches=12, wins=5),
                Team(name='JDG', league='LPL', game='英雄联盟', total_matches=18, wins=10),
                Team(name='TES', league='LPL', game='英雄联盟', total_matches=16, wins=8)
            ]
            db.session.add_all(teams_data)
            db.session.commit()
            
            # 添加示例比赛记录
            t1 = Team.query.filter_by(name='T1').first()
            gen = Team.query.filter_by(name='GEN').first()
            drx = Team.query.filter_by(name='DRX').first()
            jdg = Team.query.filter_by(name='JDG').first()
            
            matches_data = [
                Match(team1_id=t1.id, team2_id=gen.id, winner_id=t1.id, 
                     investment=100, return_amount=200, match_date=datetime.strptime('2023-04-01', '%Y-%m-%d')),
                Match(team1_id=drx.id, team2_id=gen.id, winner_id=gen.id, 
                     investment=150, return_amount=100, match_date=datetime.strptime('2023-04-02', '%Y-%m-%d')),
                Match(team1_id=t1.id, team2_id=jdg.id, winner_id=t1.id, 
                     investment=200, return_amount=400, match_date=datetime.strptime('2023-04-03', '%Y-%m-%d'))
            ]
            db.session.add_all(matches_data)
            db.session.commit()
    
    return app